package com.jus.player.fragment;

import static com.jus.player.api.OkHttpHelper._DATA;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson2.JSONObject;
import com.jus.player.R;
import com.jus.player.activity.home.JsPlayerActivity;
import com.jus.player.activity.my.RechargeActivity;
import com.jus.player.adapter.UnlockDialogAdapter;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;
import com.jus.player.entity.VideoEntity;
import com.jus.player.util.CommonUtils;
import com.jus.player.widget.VerticalViewPager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link BaseFragment} subclass.
 * Use the {@link UnlockDialogFragment#newInstance} factory method to
 * create an instance of this fragment.
 * 解锁短剧的弹窗
 */
public class UnlockDialogFragment extends DialogFragment implements UnlockDialogAdapter.OnItemCheckBoxClickListener {

    private final List<VideoEntity> mVideoList;
    private final int mPosition;
    /**
     * 需要解锁的剧集
     */
    private final List<Integer> episodes = new ArrayList<>();
    private UnlockDialogAdapter adapter;

    private TextView title;
    private TextView textAllFb;
    private TextView tipDiscountText;
    private Button btnConfirmUnlock;
    private VerticalViewPager mViewPager;
    private JsPlayerActivity activity;

    private static final long AUTO_CLOSE_DELAY = 10000; // 30 seconds
    private Handler handler;
    private Runnable autoCloseRunnable;
    /**
     * 标志位，用于跟踪是否通过按钮关闭
     */
    private boolean isClosedByButton = false;


    public UnlockDialogFragment(List<VideoEntity> videoList, int position, VerticalViewPager viewPager, JsPlayerActivity activity) {
        this.mVideoList = videoList;
        this.mPosition = position;
        this.mViewPager = viewPager;
        this.activity = activity;
    }

    public static UnlockDialogFragment newInstance(List<VideoEntity> videoList, int position, VerticalViewPager viewPager, JsPlayerActivity activity) {
        return new UnlockDialogFragment(videoList, position, viewPager, activity);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_unlock_dialog, container, false);
        // 初始化视图
        Button cbAllSelect = view.findViewById(R.id.cb_all_select);
        btnConfirmUnlock = view.findViewById(R.id.btnConfirmUnlock);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerViewEpisodes);
        title = view.findViewById(R.id.title);
        textAllFb = view.findViewById(R.id.all_fb);
        tipDiscountText = view.findViewById(R.id.tipDiscountText);


        // 设置集数选择器
        adapter = new UnlockDialogAdapter(episodes, this, mVideoList.get(mPosition).getEpisode());
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyclerView.setAdapter(adapter);

        // 初始化集数数据
        getUnlockEpisode();
        // 解锁全部按钮点击事件
        if (mPosition == 0) {
            adapter.selectAll(true);
        }
        cbAllSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 处理支付逻辑
                handlePayment(episodes);
            }
        });
        // 解锁按钮点击事件
        btnConfirmUnlock.setOnClickListener(v -> {
            List<Integer> selectedEpisodes = adapter.getSelectedEpisodes();
            if (adapter.getSelectedEpisodes().isEmpty()) {
                // 提示用户选择集数
                CommonUtils.showToastAsync(activity, "请选择解锁剧集");
                return;
            }
            // 处理支付逻辑
            handlePayment(selectedEpisodes);
        });
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        // 在布局文件中设置宽度无效
        if (getDialog() != null && getDialog().getWindow() != null) {
            getDialog().getWindow()
                    .setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                            WindowManager.LayoutParams.WRAP_CONTENT);
            //window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // 设置背景透明
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        //限制点击弹窗外关闭弹窗
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }

    /**
     * 处理支付F币
     *
     * @param success
     */
    private void handlePaymentResult(Boolean success) {
        CommonUtils.hideLoading(activity);
        if (success) {
            isClosedByButton = true;
            // 解锁成功，继续播放视频
            //mViewPager.setCurrentItem(mPosition);
            dismiss();
            CommonUtils.showToastAsync(activity, getString(R.string.unlock_success));
        } else {
            startActivity(new Intent(getActivity(), RechargeActivity.class));
            CommonUtils.showToastAsync(activity, getString(R.string.balance_not_enough));
        }
    }

    /**
     * 网络请求：消费F币
     *
     * @param selectedEpisodes
     */
    private void handlePayment(List<Integer> selectedEpisodes) {
        CommonUtils.showLoading(activity);
        int beforeFb = selectedEpisodes.size() * AppConfig.EPISODE_PRICE;
        int afterFb = (int) (beforeFb * (
                (selectedEpisodes.size() >= AppConfig.DISCOUNT_COUNT
                        || episodes.size() == selectedEpisodes.size())
                        ? (mVideoList.get(mPosition).getDiscount() / 10) : 1));
        Map<String, Object> params = new HashMap<>();
        params.put("amount", afterFb);
        params.put("episode", selectedEpisodes);
        params.put("tvId", mVideoList.get(mPosition).getId());
        params.put("all", episodes.size() == selectedEpisodes.size());
        Log.e("使用F币解锁短剧", ">>>>>，请求参数：" + params);
        OkHttpHelper.getInstance(activity).postJsonAsync(ApiConfig.CONSUME_UNLOCK_TV, params,
                new OkHttpHelper.HttpCallback() {
                    @Override
                    public void onSuccess(String res) {
                        JSONObject resJo = JSONObject.parseObject(res);
                        Boolean success = resJo.getBoolean(_DATA);
                        requireActivity().runOnUiThread(() -> handlePaymentResult(success));
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        CommonUtils.hideLoading(activity);
                        CommonUtils.showToastAsync(activity, e.getMessage());
                    }
                });
    }

    /**
     * 获取需要解锁视频数据，和更新UI
     */
    private void getUnlockEpisode() {
        episodes.clear();
        VideoEntity current = mVideoList.get(mPosition);
        title.setText(current.getTitle());
        for (VideoEntity v : mVideoList) {
            if (!v.getUnlockState()) {
                episodes.add(v.getEpisode());
            }
        }
        int allFb = (int) (episodes.size() * AppConfig.EPISODE_PRICE * (current.getDiscount() / 10));
        String text = getString(R.string.tip_all_unlock_savefb, episodes.size() * AppConfig.EPISODE_PRICE - allFb);
        textAllFb.setText(text);
    }

    /**
     * 根据选集触发 更新选集页面数据
     */
    @Override
    public void onClickUpdateData() {
        //根据adapter中checkBox数据改变动态更新UI数据
        List<Integer> selectedEpisodes = adapter.getSelectedEpisodes();
        int beforeFb = selectedEpisodes.size() * AppConfig.EPISODE_PRICE;
        int afterFb = (int) (beforeFb * (selectedEpisodes.size() >= AppConfig.DISCOUNT_COUNT
                ? (mVideoList.get(mPosition).getDiscount() / 10) : 1));
        int i = beforeFb - afterFb;
        tipDiscountText.setText(getString(R.string.tip_discount, selectedEpisodes.size(), i));
        if (afterFb > 0) {
            btnConfirmUnlock.setText(getString(R.string.fb_unlock, afterFb));
        } else {
            btnConfirmUnlock.setText(getString(R.string.unlockImmediately));
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        // 弹窗打开后，开启子线程延迟10s，判断弹窗还没有关闭则暂停视频播放
        handler = new Handler();
        autoCloseRunnable = new Runnable() {
            @Override
            public void run() {
                activity.vv.pause();
            }
        };
        // Start the auto-close timer
        handler.postDelayed(autoCloseRunnable, AUTO_CLOSE_DELAY);
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        if (handler != null) {
            handler.removeCallbacks(autoCloseRunnable);
        }
        //如果弹窗是返回按钮关闭的，则触发父级返回上级
        if (!isClosedByButton) {
            listener.onDialogClosedByBack();
        } else {
            listener.onDialogClosedFlushData(mPosition);
        }
    }

    // 持有回调接口的引用
    private OnDialogCloseListener listener;

    // 提供一个方法来设置回调接口
    public void setOnDialogCloseListener(OnDialogCloseListener listener) {
        this.listener = listener;
    }

    // 定义一个回调接口
    public interface OnDialogCloseListener {
        /**
         * 弹窗是返回关闭的
         */
        void onDialogClosedByBack();

        /**
         * 弹窗是解锁完成关闭触发刷新数据
         */
        void onDialogClosedFlushData(int position);
    }
}